package com.dhx.dao.impl;

import com.dhx.dao.TongjiDao;
import com.dhx.pojo.Tongji;
import com.dhx.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TongjiDaoImpl implements TongjiDao {
    @Override
    public int addInfo(Tongji tongji) {
        String sql = "insert into t_tongji values (?,?,?,?)";
        Object[] objs = {tongji.getDate(), tongji.getCno(), tongji.getMajor(), tongji.getArea()};
        return DBUtil.excuteDML(sql, objs);
    }

    @Override
    public int deleteInfoById(String cno) {
        String sql = "delete from t_tongji where cno= ? ";
        Object[] objs = {cno};
        System.out.println(cno);
        return DBUtil.excuteDML(sql, objs);
    }

    @Override
    public int updateInfo(Tongji tongji) {
        String sql = "update t_tongji set date=?,major=?,area=? where cno=?";
        Object[] objs = {tongji.getDate(), tongji.getMajor(), tongji.getArea(), tongji.getCno()};
        System.out.println(DBUtil.excuteDML(sql, objs));
        return 1;
    }

    @Override
    public Tongji queryInfoById(String no) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_tongji where cno=?";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        try {
            ps.setString(1, no);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        ResultSet rs = null;
        Tongji tongji = null;
        try {
            rs = ps.executeQuery();
            if (rs.next()) {
                tongji = new Tongji(rs.getString("date"), rs.getString("cno"), rs.getString("major"), rs.getString("area"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return tongji;
    }

    @Override
    public List<Tongji> queryInfoes() {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_tongji";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        ResultSet rs = null;
        List<Tongji> list = new ArrayList<Tongji>();
        try {
            rs = ps.executeQuery();
            while (rs.next()) {
                Tongji tongji = new Tongji(rs.getString("date"), rs.getString("cno"), rs.getString("major"), rs.getString("area"));
                list.add(tongji);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return list;
    }
}
